<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >

  <div style="height: 50px;">
    <el-button @click="openDialog" :disabled="props.isDisabled">批量新增</el-button>
    <el-button @click="handleAdd" >新增明细</el-button>
    <stockForm ref="formRefAdd" :warehouseId="props.warehouseId" :locationId="props.locationId" @success="handleSuccess" />
    <stockForm2 ref="formRefAdd2" :warehouseId="props.warehouseId" :locationId="props.locationId" @success2="handleSuccess2" />

  </div>


    <el-table :data="formData" class="-mt-10px"  style="height: 340px;" border>
      <el-table-column label="序号" type="index" width="100" />

      <el-table-column label="存货编码" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryCode`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventoryCode" placeholder="请输入存货编码"  @click="openDialog2($index)"   :disabled="props.isDisabled" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="存货名称" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryName`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventoryName" placeholder="请选择存货名称"  @click="openDialog2($index)"   :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="规格型号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventorySpecModel`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventorySpecModel" placeholder="请输入规格型号"  @click="openDialog2($index)"   :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryUnitName`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventoryUnitName" placeholder="请输入单位"  @click="openDialog2($index)"   :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>


      <el-table-column label="数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.qty`" :rules="formRules.qty" class="mb-0px!">
            <el-input v-model="row.qty" placeholder="请输入数量" @input="calculateValues($index)" :disabled="props.isDisabled" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="可盘点数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.checkQty`" :rules="formRules.qty" class="mb-0px!">
            <el-input v-model="row.checkQty" placeholder="请输入数量" :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.cbmemo`" :rules="formRules.cbmemo" class="mb-0px!">
            <el-input v-model="row.cbmemo" placeholder="请输入备注" :disabled="props.isDisabled"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>

</template>
<script setup lang="ts">
import { CheckvouchApi } from '@/api/wms/checkvouch'
import stockForm from './CheckStockForm.vue';
import { StockApi, StockLogVO } from '@/api/wms/stock'
import stockForm2 from './CheckStockForm2.vue';

const props = defineProps<{
  pid: undefined // 主表ID（主表的关联字段）
  warehouseId: undefined // 主表ID（主表的关联字段）
  isDisabled: boolean | undefined // 是否禁用表单           
  locationId: undefined // 主表ID（主表的关联字段）

}>()
const selectLoading = ref(false) // 表单的加载中
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  required: [{ required: true, message: '不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const stockList = ref([] as StockLogVO[]); // 存货列表


/** 查询存货 */
const remoteStock = async () => {
      stockList.value = await StockApi.getStockLogUseAll()
}

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.pid,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      console.log(val)
      formLoading.value = true
      const initialData = await CheckvouchApi.getCheckvouchsListByPid(val)
      formData.value = await Promise.all(initialData.map(async (item) => {
        if (item.stockId) {
          const inventory = await CheckvouchApi.getCheckvouchs(item.id);
          const stock =await StockApi.getStock(item.stockId);
          return {
            ...item,
            inventoryName: stock.inventoryName,
            inventoryCode: stock.inventoryCode,
            inventorySpecModel: stock.inventorySpecModel,
            inventoryUnitName: stock.inventoryUnitName,

          };
         
        }
      
        return item;
      
      }));

    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    pid: undefined,
    cinvcode: undefined,
    cbatch: undefined,
    cposcode: undefined,
    qty: undefined,
    price: undefined,
    irate: undefined,
    itaxprice: undefined,
    imoney: undefined,
    itax: undefined,
    isum: undefined,
    cbmemo: undefined,
    createBy: undefined,
    updateBy: undefined,
    
  }
  row.pid = props.pid
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}



/** 处理存货编码选择变化 */
const handleStockChange = (value, row) => {
  const selectedInventory = stockList.value.find(item => item.id === value);
  if (selectedInventory) {
    row.stockId = selectedInventory.id;
    row.inventoryName = selectedInventory.inventoryName;
    row.inventoryCode = selectedInventory.inventoryCode;
    row.inventorySpecModel = selectedInventory.inventorySpecModel;
    row.checkQty = selectedInventory.qty;
    row.useQty = selectedInventory.useQty;
    row.irate = selectedInventory.irate;
    row.price = selectedInventory.price;
    row.itaxprice = selectedInventory.itaxprice;
  }
};

//批量新增代码

const formRefAdd = ref(null); // 确保变量名唯一

const openDialog = () => {
  if(props.warehouseId==undefined)
  {
    ElMessage.warning(`仓库不能为空`);
  }
  else{
    // 打开弹窗的逻辑
    formRefAdd.value.open(); // 假设子组件有一个 open 方法
  }

};

const handleSuccess = (formData) => {
  // 处理 success 事件的逻辑
  console.log('Success event received with data:', formData)
  // 可以在这里调用 API 获取数据等
  const inventoryCodes = formData.inventoryCode;
  console.log('Selected inventory codes:', inventoryCodes);
  // 调用确认选择的方法
  confirmSelection(inventoryCodes);
};


/** 确认选择的存货编码 */
const confirmSelection = async (inventoryCodes: any[]) => {
  try {
    formLoading.value = true;
    const selectedInventoriesData = await Promise.all(inventoryCodes.map(async (id) => {
      const stockLog = await StockApi.getStock(id);
      return {
        id: undefined,
        stockId: id,
        inventoryName: stockLog.inventoryName,
        inventoryCode: stockLog.inventoryCode,
        inventoryUnitName: stockLog.inventoryUnitName,
        inventorySpecModel: stockLog.inventorySpecModel,
        checkQty: stockLog.qty,
        irate: stockLog.irate,
        price: stockLog.price,
        itaxprice: stockLog.itaxprice,
        imoney: stockLog.imoney,
        itax: stockLog.itax,
        isum: stockLog.isum,
        cbmemo: stockLog.cbmemo,
        cbatch:stockLog.batchCode,
        cposcode:stockLog.locationName
      };
    }));
    formData.value.push(...selectedInventoriesData);
  } finally {
    formLoading.value = false;
    selectedInventories.value = []; // 重置选中的存货编码
  }
};


const calculateValues = (index: number) => {
  const row = formData.value[index];

  // const itaxprice = parseFloat(row.itaxprice);
    const qty = parseFloat(row.qty);
    // const irate = parseFloat(row.irate);
    const checkQty=parseFloat(row.checkQty);

    if (qty > checkQty) {
      ElMessage.warning(`数量不能超过 ${checkQty}`);
      row.qty = checkQty;
    }


  // if (row.itaxprice && row.qty && row.irate) {
 
  //   // 计算单价
  //   const price = itaxprice / (1 + irate / 100);
  //   row.price = price.toFixed(2);

  //   // 计算金额
  //   const imoney = itaxprice * qty;
  //   row.imoney = imoney.toFixed(2);

  //   // 计算税额
  //   const itax = imoney - (price * qty);
  //   row.itax = itax.toFixed(2);

  //   // 计算价税合计
  //   const isum = imoney;
  //   row.isum = isum.toFixed(2);
  // }
};

// 点击弹出框内容

const formRefAdd2 = ref(null); // 确保变量名唯一
const selectedRowIndex = ref(-1); // 用于存储被点击行的索引

const openDialog2 = (index) => {

  if(props.warehouseId==undefined)
  {
    ElMessage.warning(`仓库不能为空`);
  }else if(props.locationId==undefined){
    ElMessage.warning(`货位不能为空`);
  }
  else{
    selectedRowIndex.value = index;
    // 打开弹窗的逻辑
    formRefAdd2.value.open(event);
    // formRefAdd.value.open(); // 假设子组件有一个 open 方法
  }

  
  
};

const handleSuccess2 = (getFormData) => {
  // 处理 success 事件的逻辑
  console.log('Success event received with data:', getFormData)
  // 可以在这里调用 API 获取数据等
  // 调用确认选择的方法
  // confirmSelection2(inventoryCodes);
  console.log('selectedRowIndex.value:', selectedRowIndex.value)

  if (selectedRowIndex.value !== -1) {
    formData.value[selectedRowIndex.value] = { ...getFormData.value, ...getFormData };
  }
};

defineExpose({ validate, getData })
</script>